package com.tianji.promotion.utils;

import com.tianji.common.exceptions.BizIllegalException;
import org.redisson.api.RLock;

public enum MyLockStrategy {
    //快速结束
    SKIP_FAST() {
        @Override
        boolean tryLock(RLock lock, MyLock myLock) throws InterruptedException {
            return lock.tryLock(0, myLock.leassTime(), myLock.util());
        }
    },
    //快速失败
    FAIL_FAST() {
        @Override
        boolean tryLock(RLock lock, MyLock myLock) throws InterruptedException {
            boolean success = lock.tryLock(0, myLock.leassTime(), myLock.util());
            if (!success) {
                throw new BizIllegalException("请求太频繁");
            }
            return success;
        }
    },
    //无限重试
    KEEP_TRYING() {
        @Override
        boolean tryLock(RLock lock, MyLock myLock){
            lock.lock(myLock.leassTime(), myLock.util());
            return true;
        }
    },
    //重试超时后结束
    SKIP_AFTER_RETRY_TIMEOUT() {
        @Override
        boolean tryLock(RLock lock, MyLock myLock) throws InterruptedException {
            return lock.tryLock(myLock.withTime(), myLock.leassTime(), myLock.util());
        }
    },
    //重试超时后失败，（抛异常）
    FAIL_AFTER_RETRY_TIMEOUT() {
        @Override
        boolean tryLock(RLock lock, MyLock myLock) throws InterruptedException {
            boolean success = lock.tryLock(myLock.withTime(), myLock.leassTime(), myLock.util());
            if (!success) {
                throw new BizIllegalException("请求太频繁");
            }
            return success;
        }
    };

    abstract boolean tryLock(RLock lock, MyLock myLock) throws InterruptedException;
}
